package com.easy.project.util;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Servlet 工具类
 */
@Component
public class ServletUtils {

    /**
     * 当前的HttpServletRequest请求
     * @return
     */
    public static HttpServletRequest currentHttpServletRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        return requestAttributes.getRequest();
    }

    /**
     * 获取当前请求的路径
     * @return
     */
    public static String getServletPath(){
        return currentHttpServletRequest().getServletPath();
    }

    /**
     * 设置属性
     * @return
     */
    public static void setAttribute(String name, Object value){
        HttpServletRequest currentHttpServletRequest = currentHttpServletRequest();
        currentHttpServletRequest.setAttribute(name,value);
    }

    /**
     * 获取属性
     * @param name
     * @return
     */
    public static Object getAttribute(String name){
        HttpServletRequest currentHttpServletRequest = currentHttpServletRequest();
        return currentHttpServletRequest.getAttribute(name);
    }

}
